<template>
  <q-page class="q-pa-md" v-loading="loading">
    <div style="position: relative; ">
      <q-breadcrumbs class="q-mb-md" style="height:50px;line-height: 40px; border-bottom: 1px dashed #ccc;">
        <q-breadcrumbs-el :label="$t('designer')" />
        <el-button type="primary" size="small" @click="toCreatePage">{{ $t('newWorkflow') }}</el-button>
        <el-input v-model="searchName" class="w-50 m-2" placeholder="搜索工作流名称" :suffix-icon="Search"
          style="max-width: 200px;position: absolute;right: 0;margin: 0;" />
      </q-breadcrumbs>
      <el-table :data="filterTableData" stripe style="width: 100%;font-size: 12px;"
        :header-cell-style="{ background: '#eee', color: '#333333' }">
        <el-table-column align="center" prop="id" label="ID" width="180" />
        <el-table-column align="center" prop="name" label="名称" width="180">
          <template #default="scope">
            <el-button link type="primary" @click="toDetailPage(scope.row.id)">{{ scope.row.name
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="version" label="最新版本" width="180" />
        <el-table-column align="center" prop="description" label="描述" width="140" />
        <el-table-column align="center" prop="create_by" label="创建人" />
        <el-table-column align="center" prop="create_time" label="创建时间" />
        <el-table-column align="center" prop="update_time" label="更新时间" />
        <el-table-column align="center" prop="labels" label="操作">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="setWorkflows(scope.$index, scope.row.id)">编辑</el-button>
            <el-button link type="primary" size="small" @click="openDeleteBox(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <div class="noData">暂无数据</div>
        </template>
      </el-table>
      <div class="row" style="justify-content: end;margin-top: 20px;" v-if="filterTableData.length > 0">
        <el-pagination background layout="total, prev, pager, next" :total=labelAssignData.count style="margin-top: 20px;"
          page-size="10" :current-page="pageData.page" @current-change="changePage" />
      </div>
      <q-dialog v-model="dialogDeleteData">
        <q-card style="width: 350px;">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px;">
              <el-icon
                style="color: #ff5656;display: inline-block;vertical-align: middle;margin-top: -3px;font-size: 20px;">
                <WarningFilled />
              </el-icon>
              删除提示
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none">
            <div>确定删除本条数据吗？</div>
            <div>删除后不可恢复，请谨慎操作！</div>
          </q-card-section>
          <q-card-actions align="right" class="text-primary">
            <el-button type="primary" plain v-close-popup>取消</el-button>
            <el-button type="primary" @click="deleteData">确认删除</el-button>
          </q-card-actions>
        </q-card>
      </q-dialog>
      <!-- 新建工作流 -->
      <el-dialog v-model="dialogSetData" title="创建工作流" width="500" :show-close="false" @close="resetForm(setDataRef)"
        :close-on-click-modal="false">
        <el-form ref="setDataRef" :model="setDataForm" :rules="setDataRules" label-position="right" label-width="130px"
          style="max-width: 460px">
          <el-form-item label="工作流名称：" prop="name">
            <el-input v-model.trim="setDataForm.name" style="width:300px" placeholder="请输入工作流名称" />
          </el-form-item>
          <el-form-item label="头像：" prop="is_pubilc">
            <el-image :src="userIcon" style="width: 50px;" fit />
          </el-form-item>
          <el-form-item label="描述：" prop="description">
            <el-input v-model.trim="setDataForm.description" style="width:300px" placeholder="请输入说明" />
          </el-form-item>
          <el-form-item label="导入工作流：" prop="description">
            <el-button type="primary" @click="importWorkflowFileDialog">选择工作流文件</el-button>
            <transition name="el-fade-in-linear">
              <div style="width: 100%;" v-if="fileName.length > 0">
                <div  class="fileNameBox">
                  {{ fileName }}</div>
              </div>
            </transition>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetForm(setDataRef)">取消</el-button>
            <el-button type="primary" @click="submitConfirm(setDataRef)">
              提交
            </el-button>
          </span>
        </template>
        <box-loading v-if="loading && loadingState" />
      </el-dialog>
      <!-- 修改工作流信息 -->
      <el-dialog v-model="setWorkflowsData" title="修改" width="500" :show-close="false" @close="resetForm(amendWorkflows)"
        :close-on-click-modal="false">
        <box-loading v-if="loading" @click.stop></box-loading>
        <el-form ref="amendWorkflows" :model="putDataForm" :rules="setDataRules" label-position="right"
          label-width="130px" style="max-width: 460px">
          <el-form-item label="工作流名称：" prop="name">
            <el-input v-model.trim="putDataForm.name" style="width:300px" placeholder="请输入工作流名称" />
          </el-form-item>
          <el-form-item label="头像：" prop="is_pubilc">
            <el-image :src="userIcon" style="width: 50px;" fit />
          </el-form-item>
          <el-form-item label="描述：" prop="description">
            <el-input v-model.trim="putDataForm.description" style="width:300px" placeholder="请输入说明" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetFormPut(amendWorkflows)">取消</el-button>
            <el-button type="primary" @click="submitConfirmPut(amendWorkflows)">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <workflow-file-dialog v-if="importWorkflowFileDialogVisible" ref="importWorkflowFileDialogRef"
      v-model:visible="importWorkflowFileDialogVisible" @dialogClose="dialogClose" @fileData="fileData" />
  </q-page>
</template>

<script setup lang="ts">
import { reactive, ref, computed, shallowRef, onUnmounted, nextTick } from "vue";
import { useRouter } from 'vue-router';
import { Search } from '@element-plus/icons-vue'
import { designerStore } from 'src/stores/designerTool/designerTool'
import { dataSetStore } from 'src/stores/dataSet'
import { modelStore } from 'src/stores/model'
import { getWorkflows, postWorkflows, deleteWorkflows, putWorkflows } from 'src/api/designerTool'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import boxLoading from 'src/components/boxLoading.vue';
import workflowFileDialog from './canvas/RightProperty/importWorkflowFileDialog.vue'
import userIcon from 'assets/dataSet/userIcon.png'
import { index } from "@antv/x6/lib/util/dom/elem";
const store = designerStore()
const router = useRouter()
const pageData = dataSetStore().pageData
const projectId = router.currentRoute.value.params.project_id
const loading = ref(false)
const searchName = ref('')
const dialogDeleteData = ref(false)
const dialogSetData = ref(false)
const setWorkflowsData = ref(false)
const amendWorkflows = ref<FormInstance>()
const setDataRef = ref<FormInstance>()
const loadingState = ref(false)
const labelAssignData = shallowRef(<Record<string,any>>
  {
    "count": 0,
    "next": "",
    "previous": "",
    "results": []
  }
)
const setDataForm = reactive(<Record<string,any>>{
  name: '',
  is_pubilc: false,
  description: '',
  dag: {},
})
const putDataForm = ref({
  name: '',
  is_pubilc: false,
  description: ''
})
const workflowId = ref()
const importWorkflowFileDialogVisible = ref(false)
const importWorkflowFileDialogRef = ref(null)
const fileName = ref('')
const setDataRules = reactive<FormRules>({
  name: [
    { required: true, message: '工作流名称不能为空', trigger: ['blur', 'change'] }
  ]
})
const filterTableData = computed(() =>
  labelAssignData.value.results.filter(
    (data:any) =>
      !searchName.value ||
      data.name.toLowerCase().includes(searchName.value.toLowerCase()) ||
      data.id.toString().toLowerCase().includes(searchName.value.toLowerCase())
  )
)
// 获取工作流数据
getDataList()
function getDataList() {
  loading.value = true
  let obj = {}
  obj = Object.assign(obj, pageData)
  getWorkflows(projectId, obj).then((res: any) => {
    labelAssignData.value = res.data
  }).catch(error => {
    console.log(error)
  }).finally(() => {
    loading.value = false
  })
}
function toCreatePage() {
  dialogSetData.value = true
}


function openDeleteBox(workflow_id: number) {
  workflowId.value = workflow_id
  dialogDeleteData.value = true
}
// 删除工作流
function deleteData() {
  loading.value = true
  dialogDeleteData.value = false
  deleteWorkflows(projectId, workflowId.value).then((res: any) => {
    ElNotification({
      title: 'Success',
      message: '删除成功',
      type: 'success',
    })
    getDataList()
  }).catch((error) => {
    console.log(error)
  })
}
function toDetailPage(workflow_id: number) {
  store.SET_WORKFLOW_ID(workflow_id)
  let id = projectId as string
  store.SET_PROJECT_ID(id)
  router.push({ name: 'designer-tool-detail', query: { project_id: projectId } })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogSetData.value = false
}
const submitConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (dialogSetData.value) {
        loadingState.value = true
        let setDataFormObj = new FormData()
        setDataFormObj.append("name", setDataForm.name)
        setDataFormObj.append("description", setDataForm.description)
        if(JSON.stringify(setDataForm.dag).length>3){
          setDataFormObj.append("dag", JSON.stringify(setDataForm.dag))
          setDataFormObj.append("icon", setDataForm.icon)
        }
        setDataFormObj.append("is_pubilc", JSON.stringify(setDataForm.is_pubilc))
        postWorkflows(projectId, setDataFormObj).then((res: any) => {
          ElMessageBox.alert('新建工作流成功', '提示', {
            confirmButtonText: 'ok',
            autofocus: false
          }).then(() => {
            dataSetStore().setPageData(1)
            getDataList()
            dialogSetData.value = false
            setDataForm.dag = {}
          })
        }).catch(error => {
          console.log(error)
          dialogSetData.value = false
        }).finally(() => {
          loadingState.value = false
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })

}
function setWorkflows(arrId: number, workflow_id: number) {
  putDataForm.value.name = labelAssignData.value.results[arrId].name
  putDataForm.value.description = labelAssignData.value.results[arrId].description
  workflowId.value = workflow_id
  setWorkflowsData.value = true
}
const resetFormPut = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  setWorkflowsData.value = false
}
const submitConfirmPut = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (setWorkflowsData.value) {
        putWorkflows(projectId, workflowId.value, putDataForm.value).then((res: any) => {
          ElNotification({
            title: 'Success',
            message: '修改工作流成功',
            type: 'success',
          })
          getDataList()
        }).catch(error => {
          console.log(error)
        }).finally(() => {
          setWorkflowsData.value = false
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

function changePage(currentPage: any) {
  dataSetStore().setPageData(currentPage)
  getDataList()
}

function importWorkflowFileDialog(row: any) {
  importWorkflowFileDialogVisible.value = true
  nextTick(() => {
    (importWorkflowFileDialogRef.value as any).init(row)
  })
}
function dialogClose() {
  importWorkflowFileDialogVisible.value = false
}
// blob转file对象
function createObjectFile(blob:any) {
   return new File([blob],blob.name);
}
function fileData(el: string) {
  setDataForm.dag = el[1]
  setDataForm.icon = createObjectFile(el[0])
  fileName.value = el[2]
}
onUnmounted(() => {
  dataSetStore().setPageData(1)
})
</script>

<style scoped lang="scss">
.uploadBox {
  .uploadBoxBtn {
    text-align: center;

    .el-image {
      width: 56px;
      height: 56px;
      display: block;
      margin: 0 auto;
    }

    div {
      font-size: 12px;
      height: 20px;
    }

  }
}

.fileNameBox {
  font-size: 13px;
  color: #333;
  word-break: break-word;
}
</style>
